package com.redisson_lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 公平锁
 */
@Service
public class GirlFailLock implements Runnable{

    private int num = 1;
    private int size = 20;

    @Autowired
    private RLockUtil lockUtil;
    private String lockKey = "thread:lock:girl";




    @Override
    public void run() {

        while (true) {

            this.start();
        }

    }
    public  void start(){

        lockUtil.fairLock(lockKey);

            if (num >= size) {
                System.out.println("sell end");
                while (Thread.currentThread().isAlive()) {
                    System.out.println(Thread.currentThread().isInterrupted());
                    System.out.println(Thread.currentThread().isAlive());
                    System.out.println("back girl:" + Thread.currentThread().getName());
                    Thread.currentThread().stop();
                    Thread.currentThread().interrupt();
                    System.out.println(Thread.currentThread().isInterrupted());
                    System.out.println(Thread.currentThread().isAlive());
                    break;
                }
                return;

            }


            try {


                System.out.println(Thread.currentThread().getName() + "lock");


                System.out.println(String.format("date:%s,girl:%s，" +
                                "\'maichu:\'%s ticket ，" +
                                "\'kucun:\'%s ticket",
                        new Date(), Thread.currentThread().getName(), this.num, this.size - this.num));
                Thread.sleep(1000);
                num++;

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                lockUtil.unFailLock(lockKey);
                System.out.println(Thread.currentThread().getName() + "unlock");
            }
        }
    }

